package ModuleFour.task01;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

public class StudentData {


    //定义保存学生信息的文件对象
    private static File file = new File("d:/student.txt");

    //自定义将集合信息保存到指定文件的方法
    public void saveFile(List studentList) {

        try {
            //创建字符流输出对象
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));

            if (studentList.size() > 0) {
                for (Object obj : studentList) {
                    //将集合中的数据遍历转换成Student类型
                    Student student = (Student) obj;
                    String studenttxt = student.getId() + "-" + student.getName() + "-" + student.getAge();
                    bw.write(studenttxt);
                    bw.newLine();//换行
                }
                bw.flush();
                bw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //自定义读取文件到集合的方法
    public void readFile() {
        BufferedReader br = null;
        try {
            //清空集合
            MainTest.studentList.clear();
            //创建字符输入流对象
            br = new BufferedReader(new FileReader(file));
            //定义读取到的每一条信息
            String studenttxt = null;
            while ((studenttxt = br.readLine()) != null) {
                //解析String类型的学生信息成为学生对象
                MainTest.studentList.add(jieStudent(studenttxt));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public Student jieStudent(String studenttxt) {
        String array[] = studenttxt.split("-");
        Student student = new Student();
        //将字符串转化为int类型
        student.setId(Integer.parseInt(array[0]));
        student.setName(array[1]);
        try {
            student.setAge(Integer.parseInt(array[2]));
        } catch (AgeException e) {
            e.printStackTrace();
        }
        return student;
    }

}
